<template>
    <div class="container">
        <div class="title mb-4">知识库</div>

        <!-- 查询表单区域 -->
        <div class="border-bottom">
            <el-form :model="formModel" ref="queryForm" label-width="100px" label-position="right">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="问题示例" prop="ruleCode">
                            <xcmg-input v-model="formModel.ruleCode" placeholder="请输入问题示例" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="答案示例" prop="description">
                            <xcmg-input v-model="formModel.description" placeholder="请输入答案示例" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="处理方式" prop="priority">
                            <xcmg-input v-model="formModel.priority" placeholder="请输入处理方式" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item>
                            <xcmg-button stoke @click="handleSearch">查询</xcmg-button>
                            <xcmg-button @click="resetForm" class="ml-2">重置</xcmg-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 操作按钮区域 -->
        <div class="button-group">
            <xcmg-button type="primary" @click="handleAdd">
                <svg-icon name="Regular" />
                <div class="spacer"></div>
                新建
            </xcmg-button>
        </div>

        <!-- 数据表格区域 -->
        <div class="table-container">
            <xcmg-table 
          :data="tableData" v-loading="loading" height="100%" style="width: 100%"
                @selection-change="handleSelectionChange">

                <el-table-column type="selection" width="55" align="center" />
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column prop="ruleCode" label="问题示例" min-width="120" show-overflow-tooltip />
                <el-table-column prop="description" label="答案示例" min-width="150" show-overflow-tooltip />
                <el-table-column prop="priority" label="参考图片" width="100" align="center" />
                <el-table-column prop="attrType" label="参考文件" min-width="120" show-overflow-tooltip />
                <el-table-column prop="attrClassify" label="处理方式" min-width="120" show-overflow-tooltip />
                <el-table-column prop="conditionsGroup" label="创建人" min-width="120" show-overflow-tooltip />
                <el-table-column prop="results" label="创建时间" min-width="120" show-overflow-tooltip />
                <el-table-column fixed="right" label="操作" width="150">
                    <template #default="{ row }">
                        <xcmg-button type="text" size="small" @click="editRow(row)">编辑</xcmg-button>
                        <xcmg-button type="text" size="small" @click="deleteRow(row)">删除</xcmg-button>
                    </template>
                </el-table-column>
            </xcmg-table>

            <!-- 分页组件 -->
            <div class="fixed-pagination">
                <xcmg-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 50, 100, 200, 500]" :total="total" background
                    layout="total,sizes,prev, pager, next,jumper" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </div>
    </div>
    <newBuilt v-model:visible="newVisible" :title="title" @queryMaterialRule="fetchTableData()"></newBuilt>
</template>
  
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance } from 'element-plus'
import { SvgIcon } from 'xcmg-components'
import { useToggle } from '@/hooks/useToggle';
import newBuilt from './components/newBuilt.vue'
import { XcmgMessageBox, XcmgMessage } from 'xcmg-components'

import { materialRuleList, materialRuleUpdata, materialRuleDelete } from '@/api/ruleBase'

// 表单数据结构
interface QueryForm {
    ruleCode: string
    description: string
    attributeType: string
    attributeCategory: string
    enabled: string
    resultField: string
}

// 表格数据结构
interface TableItem {
    id: number
    ruleCode: string
    description: string
    priority: number
    enabled: boolean
    attributeType: string
    attributeCategory: string
    conditionConfig: string
    resultConfig: string
    errorCode: string
    errorMessage: string
    creator: string
    createTime: string
}

// 表单引用
const queryForm = ref<FormInstance>()

// 表单数据
const formModel = reactive({
    ruleCode: '',
    description: '',
    priority: '',
    attrType: '',
    attrClassify: '',
    active: '',
    results: ''
})

// 分页数据
const pagination = reactive({
    page: 1,
    pageSize: 10,
    total: 0
})
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)


// 表格数据
const tableData = ref<TableItem[]>([])
const loading = ref(false)


const selectedRows = ref<TableItem[]>([])
const title = ref()

const [newVisible, newBuiltVisible] = useToggle();


// 获取表格数据
const fetchTableData = async () => {
    try {
        loading.value = true

        // 构造查询参数
        const params = {
            pageNo: currentPage.value,
            pageSize: pageSize.value,
            query: {
                ruleCode: formModel.ruleCode,
                description: formModel.description,
                priority: formModel.priority,
                attrType: formModel.attrType,
                attrClassify: formModel.attrClassify,
                active: formModel.active === '' ? null : formModel.active === 'true',
                results: formModel.results === '' ? null : formModel.results
            }
        }

        // 调用API接口
        const res = await materialRuleList(params)

        // 更新表格数据和分页信息
        tableData.value = res.data || []
        total.value = res.total || 0

    } catch (error) {
        console.error('获取数据失败:', error)
        tableData.value = []
        total.value = 0
    } finally {
        loading.value = false
    }
}


// 查询操作
const handleSearch = () => {
    currentPage.value = 1  // 重置到第一页
    fetchTableData()
}

// 重置表单
const resetForm = () => {
    if (queryForm.value) {
        queryForm.value.resetFields()
    }
    handleSearch()
}

// 分页变化处理
const handleSizeChange = (size: number) => {
    pageSize.value = size
    fetchTableData()
}

const handleCurrentChange = (page: number) => {
    currentPage.value = page
    fetchTableData()
}

// 行选择变化
const handleSelectionChange = (rows: TableItem[]) => {
    selectedRows.value = rows
}

// 新增任务
const handleAdd = () => {
    title.value = '新建'
    newBuiltVisible()
    console.log('打开新增对话框')
}


// 编辑行
const editRow = (row: TableItem) => {
    title.value = '编辑'
    newBuiltVisible()
    console.log('编辑行:', row)
}

// 删除行
const deleteRow = (row: TableItem) => {
    XcmgMessageBox.prompt('此操作将永久删除数据，继续吗？', '告警类', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
        showInput: false,
        customClass: 'xcmg-message-box--warning',
        // inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
        // inputPlaceholder: '请输入我知道了',
        // inputErrorMessage: '请认真阅读并填写内容后再点击确定'
    })
        .then(async () => {
            const res = await materialRuleDelete({
                uid: row.uid
            })
            fetchTableData()
            XcmgMessage({
                message: '删除成功',
                type: 'success',
                plain: true,
                showClose: true
            })
        })
        .catch(() => { })
}

// 初始化数据
onMounted(() => {
    fetchTableData()
})
</script>
  
<style scoped lang="less">
.container {
  padding: 20px;
  height: calc(100vh - 64px - 56px - 40px);
  display: flex;
  flex-direction: column;
}

.title {
  font-weight: bold;
  font-size: 20px;
}

.mb-4 {
  margin-bottom: 16px;
}

.border-bottom {
  border-bottom: 1px solid #e5e7eb;
}

.button-group {
  padding: 16px 0;
  display: flex;
  gap: 12px;
}

.spacer {
  width: 8px;
}

/* 表格容器：占据剩余空间 */
.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}
/* 表格：允许滚动，限制最大高度 */

.fixed-pagination {
  position: sticky;
  bottom: 0;
  background: #fff;
  padding-top: 20px;
  display: flex;
  justify-content: flex-end;
  z-index: 1;
}

:deep(.el-form-item__content) {
    justify-content: flex-end;
}
</style>